package org.jeecg.modules.qyxxora.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.modules.redisson.client.RedissonLockClient;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.fk.service.IIndexManageService;
import org.jeecg.modules.qyxx.entity.req.BgNsrjbxxReq;
import org.jeecg.modules.qyxx.entity.resp.BgPjmoXjVo;
import org.jeecg.modules.qyxx.entity.resp.BgPjmoXjVoDataPro;
import org.jeecg.modules.qyxx.entity.resp.BgTjgkVo;
import org.jeecg.modules.qyxx.service.IBgSjmkjgOrderService;
import org.jeecg.modules.qyxx.util.DateUtils;
import org.jeecg.modules.qyxxora.entity.ResetIndexLog;
import org.jeecg.modules.qyxxora.entity.ZbjkScyszbjcMx;
import org.jeecg.modules.qyxxora.mapper.ZbjkScyszbjcMxMapper;
import org.jeecg.modules.qyxxora.service.IResetIndexLogService;
import org.jeecg.modules.qyxxora.service.IStatisticsService;
import org.jeecg.modules.qyxxora.service.IZbjkScyszbjcMxService;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 生产要素指标监测明细
 * @Author: jeecg-boot
 * @Date: 2021-12-23
 * @Version: V1.0
 */
@Slf4j
@Service
public class ZbjkScyszbjcMxServiceImpl extends ServiceImpl<ZbjkScyszbjcMxMapper, ZbjkScyszbjcMx> implements IZbjkScyszbjcMxService {
    @Autowired
    private ISysDictService sysDictService;
    @Autowired
    private IIndexManageService indexManageService;
    @Autowired
    private IStatisticsService statisticsService;
    @Autowired
    private IBgSjmkjgOrderService bgSjmkjgOrderService;
    @Autowired
    private IResetIndexLogService resetIndexLogService;
    @Autowired
    private RedissonLockClient redissonLock;
    private static final String RESET_INDEX_PROCESS_LOCK = "reset-index-process-lock:";

    @Override
    public List<BgTjgkVo> tjgk(BgNsrjbxxReq req) {
        List<BgTjgkVo> list = new ArrayList<>();
        String year = DateUtils.getInstance().getYearToStr(req.getJssj());
        String jssjMaxssny = statisticsService.selectScyszbjcMaxSsny(year);
        if (jssjMaxssny == null) {
            jssjMaxssny = year + "12";
        }
        //指标监测数据中最大年月
        String maxSsny = statisticsService.selectScyszbjcMaxSsny(null);
        //获取加工数据最大年月，如果当年份最大月份大于数据最大年月，则取最大年月
        if (jssjMaxssny.compareTo(maxSsny) > 0) {
            jssjMaxssny = maxSsny;
        }
        // 指标类型
        List<DictModel> zblx = sysDictService.queryDictItemsByCode("zbgl_zblx");
        for (DictModel dictModel : zblx) {
            String zbType = dictModel.getValue();
            BgTjgkVo vo = new BgTjgkVo();
            // 获取对应指标类型的指标总数
            Integer amount = indexManageService.listByZblx(zbType);
            vo.setAmount(amount);
            vo.setIndexName(dictModel.getText());
            Integer number = baseMapper.getQyYczbZs(req.getDjxh(), jssjMaxssny, zbType);
            vo.setNumber(number);
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<BgPjmoXjVo> pjmxxj(BgNsrjbxxReq req) {
        //结束时间的所属年月数据最大月份yyyyMM格式,如果没有就取该年的12月份
        String year = DateUtils.getInstance().getYearToStr(req.getJssj());
        String jssjMaxssny = statisticsService.selectScyszbjcMaxSsny(year);
        if (StringUtils.isEmpty(jssjMaxssny)) {
            jssjMaxssny = year + "12";
        }
        //指标监测数据中最大年月
        String maxSsny = statisticsService.selectScyszbjcMaxSsny(null);
        if  (StringUtils.isEmpty(maxSsny)) {
            return new ArrayList<>();
        }
        //获取加工数据最大年月，如果当年份最大月份大于数据最大年月，则取最大年月
        if (jssjMaxssny.compareTo(maxSsny) > 0) {
            jssjMaxssny = maxSsny;
        }
        // 指标类型
        List<DictModel> zblx = sysDictService.queryDictItemsByCode("zbgl_zblx");
        List<BgPjmoXjVo> list = new ArrayList<>();
        for (DictModel dictModel : zblx) {
            BgPjmoXjVo xjVo = new BgPjmoXjVo();
            List<BgPjmoXjVoDataPro> proList = baseMapper.getPjmxxj(req.getDjxh(), jssjMaxssny, dictModel.getValue());
            /*setYjxqValue(proList);
            List<BgPjmoXjVoData> xjVoData = new ArrayList<>();
            for (BgPjmoXjVoDataPro pro : proList) {
                BgPjmoXjVoData data = new BgPjmoXjVoData();
                BeanUtils.copyProperties(pro, data);
                xjVoData.add(data);
            }*/
            xjVo.setData(proList);
            xjVo.setText(dictModel.getText());
            list.add(xjVo);
        }
        return list;
    }

    @Autowired
    private ISysUserService sysUserService;

    public void setYjxqValue(List<BgPjmoXjVoDataPro> voData) {
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Set<String> roleNameListString = sysUserService.getUserRolesSet(loginUser.getUsername());
        // 如果该用户为超级管理员 生产要素系统管理员或者生产要素管理岗时 可以查看阈值上下限
        if (roleNameListString.contains("superAdmin") || roleNameListString.contains("sysProvinceAdmin") || roleNameListString.contains("provinceAdmin")) {
            for (BgPjmoXjVoDataPro data : voData) {
                // ZbjkScyszbjcMx zbjkScyszbjcMx = baseMapper.selectById(data.getMxid());
                String yjxq = data.getYjxq();
                BigDecimal fzSx = data.getFzSx();
                if (fzSx != null) {
                    yjxq = yjxq + ",阈值上线" + fzSx + "%";
                }
                BigDecimal fzXx = data.getFzXx();
                if (fzXx != null) {
                    yjxq = yjxq + ",阈值下线" + fzXx + "%";
                }
                data.setYjxq(yjxq);
            }
        }
    }

    @Override
    public void callZbjkZbjhListPro(String ssrq) {
        baseMapper.callZbjkZbjhListPro(ssrq);
    }


    // @JLock(lockKey = "reset-index-process-lock", expireSeconds = 600000L)
    @Override
    public boolean resetIndexProcess(String ssrq) {
        DateTime time = DateUtil.parse(ssrq, "yyyyMM");
        Calendar cal = Calendar.getInstance();
        cal.setTime(time);
        //获取某月最大天数
        int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
        //设置日历中月份的最大天数
        cal.set(Calendar.DAY_OF_MONTH, lastDay);
        ssrq = DateUtil.format(cal.getTime(), "yyyyMMdd");

        boolean flag = true;
        ResetIndexLog log = new ResetIndexLog();
        Date now = new Date();
        log.setCommitDate(now);
        log.setCzny(DateUtil.format(DateUtil.parse(ssrq, "yyyyMMdd"), "yyyy年MM月"));
        log.setStatus("1");
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        log.setOperator(user.getRealname() + "(" + user.getPhone() + ")");
        try {
            if (redissonLock.tryLock(RESET_INDEX_PROCESS_LOCK, -1, 600)) {
                    callZbjkZbjhListPro(ssrq);
                log.setStatus("2");
                // Thread.sleep(30000);
                redissonLock.unlock(RESET_INDEX_PROCESS_LOCK);
            } else {
                ZbjkScyszbjcMxServiceImpl.log.error("获取锁失败");
                log.setStatus("3");
                log.setErrorMessage("获取锁失败, 已经有当前月份在处理中");
                flag = false;
            }
        } catch (Exception e) {
            ZbjkScyszbjcMxServiceImpl.log.error("调度重跑指标任务异常");
            flag = false;
            ZbjkScyszbjcMxServiceImpl.log.error("异常信息:" + e.getMessage());
            log.setStatus("3");
            log.setErrorMessage(e.getMessage());
        } finally {
            resetIndexLogService.save(log);
        }
        return flag;
    }
}
